package com.ruoyi.canteen.controller.v1;

import com.alibaba.fastjson.JSONObject;
import com.auth0.jwt.interfaces.Claim;
import com.ruoyi.canteen.domain.CanteenOrderAddress;
import com.ruoyi.canteen.domain.CanteenQrAddress;
import com.ruoyi.canteen.domain.CanteenUser;
import com.ruoyi.canteen.service.ICanteenOrderAddressService;
import com.ruoyi.canteen.service.ICanteenQrAddressService;
import com.ruoyi.canteen.utils.BeanCopyUtils;
import com.ruoyi.canteen.utils.JwtToken;
import com.ruoyi.canteen.vo.CanteenOrderAddressVo;
import com.ruoyi.canteen.vo.CanteenQrAddrVo;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.DictUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.service.ISysDictTypeService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * @Author Ryan
 * @Date 2021/9/19 15:48
 * @Version 1.0
 */
@RestController
@RequestMapping("/v1/address")
public class AddressApiController extends BaseController {

    private static final Logger log = LoggerFactory.getLogger(AddressApiController.class);

    @Autowired
    private ICanteenOrderAddressService canteenOrderAddressService;

    @Autowired
    private ICanteenQrAddressService canteenQrAddressService;

    @Autowired
    private ISysDictTypeService dictTypeService;

    /**
     * 根据登录用户，查询订餐地址列表
     * @param token 用户token
     */
    @GetMapping("/listByUser/{token}")
    public TableDataInfo listByUser(@PathVariable("token") String token)
    {
        Optional<Map<String, Claim>> optionalMap = JwtToken.getClaims(token);
        if(optionalMap.isPresent()){
            Map<String, Claim> map = optionalMap.get();
            Long uid = map.get("uid").asLong();
            List<CanteenOrderAddressVo> list =
                    canteenOrderAddressService.selectCanteenOrderAddressListByUserId(uid, null);
            return getDataTable(list);
        }else {
            return getDataTable(null);
        }
    }

    /**
     * 获取订餐地址详细信息
     */
    @GetMapping(value = "/getInfo")
    public AjaxResult getInfo(@RequestParam("token") String token,@RequestParam("id")  Long id)
    {
        Optional<Map<String, Claim>> optionalMap = JwtToken.getClaims(token);
        if(optionalMap.isPresent()) {
            Map<String, Claim> map = optionalMap.get();
            Long uid = map.get("uid").asLong();
            CanteenOrderAddress address = new CanteenOrderAddress();
            address.setUserId(uid);
            address.setId(id);
            return AjaxResult.success(canteenOrderAddressService.selectCanteenOrderAddressList(address).get(0));
        }else{
            return AjaxResult.error("授权失败");
        }

    }

    @GetMapping(value = "/getDefault")
    public AjaxResult getDefault(@RequestParam("token") String token)
    {
        Optional<Map<String, Claim>> optionalMap = JwtToken.getClaims(token);
        if(optionalMap.isPresent()) {
            Map<String, Claim> map = optionalMap.get();
            Long uid = map.get("uid").asLong();
//            CanteenOrderAddress address = new CanteenOrderAddress();
//            address.setUserId(uid);
//            address.setIsDefault(1);
            // TODO 默认地址错误处理 java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
            List<CanteenOrderAddressVo> list = canteenOrderAddressService.selectCanteenOrderAddressListByUserId(uid, 1);
            if(list.size() > 0){
                return AjaxResult.success(list.get(0));
            }else{
                return AjaxResult.error("无默认地址");
            }
        }else{
            return AjaxResult.error("授权失败");
        }
    }

    @GetMapping(value = "/setDefault")
    public AjaxResult setDefault(@RequestParam("token") String token, @RequestParam("id") Long id)
    {
        Optional<Map<String, Claim>> optionalMap = JwtToken.getClaims(token);
        if(optionalMap.isPresent()) {
            Map<String, Claim> map = optionalMap.get();
            Long uid = map.get("uid").asLong();
            return toAjax(canteenOrderAddressService.setDefaultCanteenOrderAddress(id, uid));
        }else{
            return AjaxResult.error("授权失败");
        }
    }

    /**
     * 新增订餐地址
     */
//    @Log(title = "订餐地址", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    public AjaxResult add(@RequestBody CanteenOrderAddressVo canteenOrderAddressVo)
    {
        String token  = canteenOrderAddressVo.getToken();
        Optional<Map<String, Claim>> optionalMap = JwtToken.getClaims(token);
        if(optionalMap.isPresent()) {
            Map<String, Claim> map = optionalMap.get();
            Long uid = map.get("uid").asLong();
            CanteenOrderAddress canteenOrderAddress = new CanteenOrderAddress();
            BeanCopyUtils.copyProperties(canteenOrderAddressVo, canteenOrderAddress);
            canteenOrderAddress.setUserId(uid);
            // 新增订餐地址，将其它地址设为非默认地址
            int result = 0;
            // 检查当前用户 + 订单地址 是否存在
            CanteenOrderAddress queryAddress = new CanteenOrderAddress();
            queryAddress.setUserId(uid);
            queryAddress.setAddress(canteenOrderAddress.getAddress());
            List<CanteenOrderAddress> dbList = canteenOrderAddressService.selectCanteenOrderAddressList(queryAddress);
            try{
                // 存在则修改
                if(dbList.size() > 0){
                    canteenOrderAddress.setId(dbList.get(0).getId());
                    result = canteenOrderAddressService.updateCanteenOrderAddress(canteenOrderAddress);
                }else{
                    // 不存在则新增
                    result = canteenOrderAddressService.insertCanteenOrderAddress(canteenOrderAddress);
                    result = result + canteenOrderAddressService.setDefaultCanteenOrderAddress(canteenOrderAddress.getId(), uid);
                }
            }catch (Exception ex){
                // 插入更新报错
                log.info("地址改动错误："+ ex.toString());
                return AjaxResult.error("操作地址失败");
            }
            return toAjax(result);
        }else{
            return AjaxResult.error("授权失败");
        }

    }

    /**
     * 修改订餐地址
     */
//    @Log(title = "订餐地址", businessType = BusinessType.UPDATE)
    @PutMapping("/update")
    public AjaxResult update(@RequestBody CanteenOrderAddressVo canteenOrderAddressVo)
    {
        String token  = canteenOrderAddressVo.getToken();
        Optional<Map<String, Claim>> optionalMap = JwtToken.getClaims(token);
        int result = 0;
        if(optionalMap.isPresent()) {
            Map<String, Claim> map = optionalMap.get();
            Long uid = map.get("uid").asLong();
            CanteenOrderAddress canteenOrderAddress = new CanteenOrderAddress();
            BeanCopyUtils.copyProperties(canteenOrderAddressVo, canteenOrderAddress);
            canteenOrderAddress.setUserId(uid);
            result = canteenOrderAddressService.updateCanteenOrderAddress(canteenOrderAddress);
            result = result + canteenOrderAddressService.setDefaultCanteenOrderAddress(canteenOrderAddress.getId(), uid);
            return toAjax(result);
        }else{
            return AjaxResult.error("授权失败");
        }

    }



    /**
     * 删除订餐地址
     */
//    @Log(title = "订餐地址", businessType = BusinessType.DELETE)
    @DeleteMapping("/invalid")
    public AjaxResult invalidCanteenOrderAddress(@RequestBody Map<String,String> reqMap)
    {
        String token = reqMap.get("token");
        Long id = Long.valueOf(reqMap.get("id"));
        Optional<Map<String, Claim>> optionalMap = JwtToken.getClaims(token);
        if(optionalMap.isPresent()) {
            Map<String, Claim> map = optionalMap.get();
            Long uid = map.get("uid").asLong();
            return toAjax(canteenOrderAddressService.invalidCanteenOrderAddressById(id, uid));
        }else{
            return AjaxResult.error("授权失败");
        }
    }

    @PostMapping("/verifyAddress")
    public AjaxResult verifyAddress(@RequestBody JSONObject jsonParam){
        String token = jsonParam.getString("token");
        String address = jsonParam.getString("address");
        Optional<Map<String, Claim>> optionalMap = JwtToken.getClaims(token);
        if(optionalMap.isPresent()) {
            Map resultMap = new HashMap();
            Map<String, Claim> map = optionalMap.get();
            Long uid = map.get("uid").asLong();
            CanteenOrderAddress orderAddress = new CanteenOrderAddress();
            orderAddress.setUserId(uid);
            orderAddress.setAddress(address);
            List<CanteenOrderAddress> list = canteenOrderAddressService.selectCanteenOrderAddressList(orderAddress);
            if(list.size() > 0){
                // 存在此地址，则将此地址设置为默认地址
                canteenOrderAddressService.setDefaultCanteenOrderAddress(list.get(0).getId(), uid);
                resultMap.put("curAddress", list.get(0));
                resultMap.put("result", true);
                return AjaxResult.success(resultMap);
            }else{
                // 不存在此地址，则跳转到新增地址
                resultMap.put("result", false);
            }
            return AjaxResult.success(resultMap);
        }else{
            return AjaxResult.error("授权失败");
        }
    }

    @GetMapping(value = "/getQrAddressById/{id}")
    public AjaxResult getQrAddressById(@PathVariable("id") Long id) {
        CanteenQrAddress qrAddress = canteenQrAddressService.selectCanteenQrAddressById(id);
        return AjaxResult.success(qrAddress);
    }

    @GetMapping(value = "/getQrAddrDetailById/{id}")
    public AjaxResult getQrAddrDetailById(@PathVariable("id") Long id) {
        CanteenQrAddrVo qrAddressVo = canteenQrAddressService.selectCanteenQrAddrDetailById(id);
        return AjaxResult.success(qrAddressVo);
    }

    @GetMapping(value = "/getAllBuildAddress")
    public AjaxResult getAllBuildAddress() {
        List<SysDictData> buildDict = dictTypeService.selectDictDataByType("location_building");
        return AjaxResult.success(buildDict);
    }

}
